from BloodSpiderModel.DjangoResponseTool.response_dict import response_dict, get_page, get_first_error
from BloodSpiderAPI.apis.user import utils as user_utils
from django import forms
from django.core.validators import RegexValidator, MinLengthValidator, MaxLengthValidator
from BloodSpiderAPI import models
from django.db.models import Q
import time


class UserForm(forms.ModelForm):
    # 添加账号验证：只能是纯数字，长度在8-11位之间
    account = forms.CharField(
        max_length=255,
        validators=[
            RegexValidator(r'^\d+$', message='账号必须为纯数字'),
            MinLengthValidator(8, message='账号长度不能少于8位'),
            MaxLengthValidator(11, message='账号长度不能超过11位')
        ],
        error_messages={
            'unique': '该账号已被注册'
        }
    )
    
    class Meta:
        model = models.User
        fields = ["username", "account", "password"]


# 创建用户API
def create_user(request):
    time.sleep(2)
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)

    form = UserForm(request.POST)
    if not form.is_valid():
        return response_dict(data=get_first_error(form), code=1, message="参数错误")

    try:
        user = form.save()
        response = user_utils.utils_model_to_dict(user, show_password=False)
        return response_dict(data=response, message="用户创建成功")
    except Exception as e:
        return response_dict(message=f"创建失败: {str(e)}", code=1)


# 删除用户API
def delete_user(request):
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)

    user_uid = request.POST.get('uid')
    if not user_uid:
        return response_dict(message="缺少用户UID参数", code=1)

    try:
        user = models.User.objects.get(uid=user_uid)
        user.delete()
        return response_dict(message="用户删除成功")
    except models.User.DoesNotExist:
        return response_dict(message="用户不存在", code=1)
    except Exception as e:
        return response_dict(message=f"删除失败: {str(e)}", code=1)


# 更新用户API
def update_user(request):
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)

    user_uid = request.POST.get('uid')
    if not user_uid:
        return response_dict(message="缺少用户UID参数", code=1)

    try:
        user = models.User.objects.get(uid=user_uid)
        update_data = {}

        # 检查并添加可更新字段
        if 'username' in request.POST and request.POST['username']:
            update_data['username'] = request.POST['username']
        if 'account' in request.POST and request.POST['account']:
            # 验证账号格式和长度
            account = request.POST['account']
            if not account.isdigit():
                return response_dict(message="账号必须为纯数字", code=1)
            if not 8 <= len(account) <= 11:
                return response_dict(message="账号长度必须在8-11位之间", code=1)
            # 检查账号是否重复
            if models.User.objects.filter(account=account).exclude(uid=user_uid).exists():
                return response_dict(message="账号已存在", code=1)
            update_data['account'] = account
        if 'password' in request.POST and request.POST['password']:
            update_data['password'] = request.POST['password']

        # 如果没有任何可更新字段
        if not update_data:
            return response_dict(message="没有提供可更新字段", code=1)

        # 手动更新字段，避免表单验证的严格限制
        for field, value in update_data.items():
            setattr(user, field, value)

        # 保存前进行数据验证
        try:
            user.full_clean()  # 手动触发模型验证
        except Exception as e:
            return response_dict(message=f"数据验证失败: {str(e)}", code=1)

        user.save()
        response = user_utils.utils_model_to_dict(user, show_password=False)
        return response_dict(data=response, message="用户更新成功")
    except models.User.DoesNotExist:
        return response_dict(message="用户不存在", code=1)
    except Exception as e:
        return response_dict(message=f"更新失败: {str(e)}", code=1)


# 查询单个用户API
def get_user(request):
    if request.method != 'GET':
        return response_dict(message="请使用GET请求", code=1)

    user_uid = request.GET.get('uid')
    if not user_uid:
        return response_dict(message="缺少用户UID参数", code=1)

    try:
        user = models.User.objects.get(uid=user_uid)
        response = user_utils.utils_model_to_dict(user, show_password=False, show_time=True)
        return response_dict(data=response, message="查询成功")
    except models.User.DoesNotExist:
        return response_dict(message="用户不存在", code=1)
    except Exception as e:
        return response_dict(message=f"查询失败: {str(e)}", code=1)


# 搜索用户API（支持模糊搜索）
def search_users(request):
    if request.method != 'GET':
        return response_dict(message="请使用GET请求", code=1)

    try:
        query = Q()

        # 用户名模糊搜索
        username = request.GET.get('username')
        if username:
            query &= Q(username__icontains=username)

        # 账号精确搜索
        account = request.GET.get('account')
        if account:
            query &= Q(account__icontains=account)

        users = models.User.objects.filter(query).order_by('-created_at')

        # 分页处理
        page_size = int(request.GET.get('page_size', 10))
        page = int(request.GET.get('page', 1))
        paginated_data = get_page(users, page_size=page_size, page_num=page)

        response = {
            "user_list": [
                user_utils.utils_model_to_dict(user, show_password=False)
                for user in paginated_data["page"]["object_list"]
            ],
        }
        del paginated_data["page"]["object_list"]
        response.update(paginated_data["page"])

        return response_dict(data=response, message="搜索成功")
    except Exception as e:
        return response_dict(message=f"搜索失败: {str(e)}", code=1)


# 用户登录API
def login(request):
    time.sleep(2)
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)

    account = request.POST.get('account')
    password = request.POST.get('password')

    if not account or not password:
        return response_dict(message="账号和密码不能为空", code=1)

    try:
        # 查找用户
        user = models.User.objects.get(account=account)

        # 验证密码
        if user.password != password:
            return response_dict(message="密码错误", code=1)

        # 登录成功，返回用户信息（不包含密码）
        response = user_utils.utils_model_to_dict(user, show_password=False, show_time=True)
        return response_dict(data=response, message="登录成功")

    except models.User.DoesNotExist:
        return response_dict(message="账号不存在", code=1)
    except Exception as e:
        return response_dict(message=f"登录失败: {str(e)}", code=1)

    